﻿using AutoMapper;
using MediatR;
using Traceability.App.Api.Application.Command.Add;
using Traceability.App.Domain;
using Traceability.App.ErrorCode;
using Traceability.App.Instructure;

namespace Traceability.App.Api.Application.Handler.Add
{
    /// <summary>
    /// 添加溯源基本信息
    /// </summary>
    public class AddTraceabilityHandler : IRequestHandler<AddTraceabilityCommand, ApiResult<TraceabilityModel>>
    {
        private readonly IBaseRepository<TraceabilityModel> traceabilityRepo;
        private readonly IMapper mapper;

        public AddTraceabilityHandler(IBaseRepository<TraceabilityModel> traceabilityRepo,IMapper mapper) 
        {
            this.traceabilityRepo = traceabilityRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<TraceabilityModel>> Handle(AddTraceabilityCommand request, CancellationToken cancellationToken)
        {
            ApiResult<TraceabilityModel> res = new ApiResult<TraceabilityModel>();
            var traceability = traceabilityRepo.GetAll().Where(x => x.IsDelete == false).FirstOrDefault();
            
            var model=mapper.Map<TraceabilityModel>(request);
            model.UpdateTime=DateTime.Now;
            model.CreateTime=DateTime.Now;
            model.UpdateName = "张三";
            model.CreateName = "张三";
           
            int i = traceabilityRepo.Add(model);
            if (i>0)
            {
                res.Code = ApiEnum.Success;
               
                res.Msg = "添加成功";
            }
            else
            {
                res.Code = ApiEnum.Success;
                
                res.Msg = "添加失败";
            }
            return Task.FromResult(res);
        }
    }
}
